package net.yxsoft.service;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.protobuf.ByteString;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import net.yxsoft.chainmaker.CryptoUtils;
import net.yxsoft.chainmaker.InitClient;
import net.yxsoft.kit.Helper;
import net.yxsoft.model.formdesigner.FnFormData;
import net.yxsoft.service.common.BaseService;
import net.yxsoft.bean.contract.BaseItem;
import net.yxsoft.bean.contract.ShareItem;
import org.chainmaker.pb.common.ChainmakerTransaction;
import org.chainmaker.pb.common.ResultOuterClass;
import org.chainmaker.pb.config.ChainConfigOuterClass;
import org.chainmaker.sdk.ChainClient;
import org.chainmaker.sdk.SdkException;
import org.chainmaker.sdk.User;


import java.math.BigInteger;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class OrderService extends BaseService {

    public static final OrderService me = new OrderService();

    /**
     * 获取指令数据
     *
     * @param chainClient  区块链客户端
     * @param orderId      指令ID
     * @param contractName 合约名称
     * @return 指令数据
     * @throws Exception 发生错误时抛出异常
     */
    public static ShareItem getOrderData(ChainClient chainClient, String orderId, String contractName) throws Exception {
        Map<String, byte[]> paramMap = new HashMap<>();
        paramMap.put("orderId", orderId.getBytes());

        ResultOuterClass.TxResponse responseInfo = null;
        try {
            responseInfo = chainClient.queryContract(contractName, "getOrderData",
                    null, paramMap, 10000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("getOrderData 执行合约结果：");
        System.out.println(responseInfo);
        String str = ByteString.copyFromUtf8(responseInfo.getContractResult().getResult().toStringUtf8()).toStringUtf8();

        return jsonObjectToShareItem(str);

    }

    /**
     * 获取状态数据
     *
     * @param chainClient  区块链客户端
     * @param stateId      状态ID
     * @param contractName 合约名称
     * @return 状态数据
     * @throws Exception 发生错误时抛出异常
     */
    public static ShareItem getStateData(ChainClient chainClient, String stateId, String contractName) throws Exception {
        Map<String, byte[]> paramMap = new HashMap<>();
        paramMap.put("stateId", stateId.getBytes());

        ResultOuterClass.TxResponse responseInfo = null;
        try {
            responseInfo = chainClient.queryContract(contractName, "getStateData",
                    null, paramMap, 10000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("getStateData 执行合约结果：");
        System.out.println(responseInfo);
        String str = ByteString.copyFromUtf8(responseInfo.getContractResult().getResult().toStringUtf8()).toStringUtf8();

        return jsonObjectToShareItem(str);

    }

    /**
     * 获取指令列表
     *
     * @param chainClient  区块链客户端
     * @param pagesize     每页显示的指令数量
     * @param pagenum      当前页数
     * @param contractName 合约名称
     * @return 包含订单信息的列表
     * @throws Exception 发生错误时抛出异常
     */
    public static ArrayList<ShareItem> getOrders(ChainClient chainClient, int pagesize, int pagenum, String contractName) throws Exception {

        Map<String, byte[]> paramMap = new HashMap<>();

        JSONObject page = new JSONObject();
        page.put("PageSize", pagesize);
        page.put("PageNum", pagenum);

        paramMap.put("data", page.toString().getBytes());

        ResultOuterClass.TxResponse responseInfo = null;
        try {
            responseInfo = chainClient.queryContract(contractName, "getOrders",
                    null, paramMap, 10000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("getOrders 执行合约结果：");
        System.out.println(responseInfo);

        if (responseInfo.getContractResult().getResult() == null || responseInfo.getContractResult().getMessage().equals("Fail")) {
            return null;
        }
        String str = ByteString.copyFromUtf8(responseInfo.getContractResult().getResult().toStringUtf8()).toStringUtf8();

        // 将字符串转换为JsonArray
        Gson gson = new Gson();
        JsonArray jsonArray = gson.fromJson(str, JsonArray.class);
        if (jsonArray == null) {
            return null;
        }

        ArrayList<ShareItem> shareItems = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            String objstr = jsonArray.get(i).toString();
            ShareItem shareItem = jsonObjectToOrderShare(objstr);
            if (shareItem == null) {
                return null;
            }
            shareItems.add(shareItem);
        }

        return shareItems;
    }

    /**
     * 获取状态列表
     *
     * @param chainClient  区块链客户端
     * @param pagesize     每页显示的订单数量
     * @param pagenum      当前页数
     * @param contractName 合约名称
     * @return 包含状态信息的列表
     * @throws Exception 发生错误时抛出异常
     */
    public static ArrayList<ShareItem> getStates(ChainClient chainClient, int pagesize, int pagenum, String contractName) throws Exception {

        Map<String, byte[]> paramMap = new HashMap<>();

        JSONObject page = new JSONObject();
        page.put("PageSize", pagesize);
        page.put("PageNum", pagenum);

        paramMap.put("data", page.toString().getBytes());

        ResultOuterClass.TxResponse responseInfo = null;
        try {
            responseInfo = chainClient.queryContract(contractName, "getStates",
                    null, paramMap, 10000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("getOrders 执行合约结果：");
        System.out.println(responseInfo);

        if (responseInfo.getContractResult().getResult() == null || responseInfo.getContractResult().getMessage().equals("Fail")) {
            return null;
        }
        String str = ByteString.copyFromUtf8(responseInfo.getContractResult().getResult().toStringUtf8()).toStringUtf8();

        // 将字符串转换为JsonArray
        Gson gson = new Gson();
        JsonArray jsonArray = gson.fromJson(str, JsonArray.class);
        if (jsonArray == null) {
            return null;
        }

        ArrayList<ShareItem> shareItems = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            String objstr = jsonArray.get(i).toString();
            ShareItem shareItem = jsonObjectToOrderShare(objstr);
            if (shareItem == null) {
                return null;
            }
            shareItems.add(shareItem);
        }

        return shareItems;
    }

    /**
     * 检查指令是否存在
     *
     * @param chainClient  区块链客户端
     * @param orderId      指令ID
     * @param contractName 合约名称
     * @return 如果订单存在，返回 true；否则返回 false
     * @throws Exception 发生错误时抛出异常
     */
    public static boolean checkOrderExist(ChainClient chainClient, String orderId, String contractName) throws Exception {

        Map<String, byte[]> paramMap = new HashMap<>();
        paramMap.put("orderId", orderId.getBytes());

        ResultOuterClass.TxResponse responseInfo = null;
        try {
            responseInfo = chainClient.queryContract(contractName, "checkOrderExist",
                    null, paramMap, 10000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("checkOrderExist 执行合约结果：");
        System.out.println(responseInfo);
        return responseInfo.getTxId() != null ? true : false;

    }

    /**
     * 检查状态是否存在
     *
     * @param chainClient  区块链客户端
     * @param stateId      状态ID
     * @param contractName 合约名称
     * @return 如果订单存在，返回 true；否则返回 false
     * @throws Exception 发生错误时抛出异常
     */
    public static boolean checkStateExist(ChainClient chainClient, String stateId, String contractName) throws Exception {

        Map<String, byte[]> paramMap = new HashMap<>();
        paramMap.put("stateId", stateId.getBytes());

        ResultOuterClass.TxResponse responseInfo = null;
        try {
            responseInfo = chainClient.queryContract(contractName, "checkStateExist",
                    null, paramMap, 10000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("checkStateExist 执行合约结果：");
        System.out.println(responseInfo);
        return responseInfo.getTxId() != null ? true : false;

    }

    /**
     * 获取指定合约中的证据项数量
     *
     * @param chainClient  区块链客户端
     * @param contractName 合约名称
     * @return 证据项数量
     * @throws Exception 发生错误时抛出异常
     */
    public static Integer getOrderSize(ChainClient chainClient, String contractName) throws Exception {

        ResultOuterClass.TxResponse responseInfo = null;
        try {
            responseInfo = chainClient.queryContract(contractName, "getOrderSize",
                    null, null, 10000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("getOrderSize 查询合约结果：");
        System.out.println(responseInfo);
        try {
            String resultString = responseInfo.getContractResult().getResult().toStringUtf8();
            Integer result = Integer.parseInt(resultString);
            return result;
        } catch (Exception e) {
//            e.printStackTrace();
            return 0;
        }

    }

    /**
     * 获取指定合约中的证据项数量
     *
     * @param chainClient  区块链客户端
     * @param contractName 合约名称
     * @return 证据项数量
     * @throws Exception 发生错误时抛出异常
     */
    public static Integer getStateSize(ChainClient chainClient, String contractName) throws Exception {

        ResultOuterClass.TxResponse responseInfo = null;
        try {
            responseInfo = chainClient.queryContract(contractName, "getStateSize",
                    null, null, 10000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("getStateSize 查询合约结果：");
        System.out.println(responseInfo);
        try {
            String resultString = responseInfo.getContractResult().getResult().toStringUtf8();
            Integer result = Integer.parseInt(resultString);
            return result;
        } catch (Exception e) {
//            e.printStackTrace();
            return 0;
        }

    }

    /**
     * 将所有证据项存入数据库
     *
     * @param chainClient  区块链客户端
     * @param contractName 合约名称
     * @return 存储成功返回 true，否则返回 false
     * @throws Exception 发生错误时抛出异常
     */
    public static boolean getAllOrdersToDb(ChainClient chainClient, String contractName) throws Exception {

        Integer allSize = getOrderSize(chainClient, contractName);

        if (allSize == 0) {
            return true;
        }

        int pagesize = 100;

        // 相除并取商
        int pagenum = allSize / pagesize;
        // 相除并取余数
        int remainder = allSize % pagesize;

        if (remainder > 0) {
            pagenum++;
        }

        //一页一页取，每次100条
        for (int ii = 1; ii <= pagenum; ii++) {
            Map<String, byte[]> paramMap = new HashMap<>();

            JSONObject page = new JSONObject();
            page.put("PageSize", pagesize);
            page.put("PageNum", pagenum);

            paramMap.put("data", page.toString().getBytes());

            ResultOuterClass.TxResponse responseInfo = null;
            try {
                responseInfo = chainClient.queryContract(contractName, "getOrders",
                        null, paramMap, 10000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("getOrders 执行合约结果：");
            System.out.println(responseInfo);

            if (responseInfo.getContractResult().getResult() == null || responseInfo.getContractResult().getMessage().equals("Fail")) {
                return false;
            }
            String str = ByteString.copyFromUtf8(responseInfo.getContractResult().getResult().toStringUtf8()).toStringUtf8();

            // 将字符串转换为JsonArray
            Gson gson = new Gson();
            JsonArray jsonArray = gson.fromJson(str, JsonArray.class);
            if (jsonArray == null) {
                return false;
            }

            for (int i = 0; i < jsonArray.size(); i++) {
                String sData = jsonArray.get(i).toString();
                JSONObject shareObject = JSONUtil.toBean(sData, JSONObject.class);
                JSONObject senderobj = shareObject.getJSONObject("Sender");
                JSONObject receiverobj = shareObject.getJSONObject("Receiver");

                FnFormData fnFormData = new FnFormData();

                String orderId = shareObject.get("OrderId").toString();
                String sType = "指令数据";
                String sName1 = "";
                String sHash1 = "";
                String sCreateTM1 = "";
                String sRemark1 = "";
                String sTxHash1 = "";
                String sName2 = "";
                String sHash2 = "";
                String sCreateTM2 = "";
                String sRemark2 = "";
                String sTxHash2 = "";
                fnFormData.setAttrib31(orderId);

                if ((senderobj != null) && (senderobj.size() > 0)) {
                    sName1 = senderobj.get("Name").toString();
                    sHash1 = senderobj.get("Hash").toString();
                    sCreateTM1 = senderobj.get("CreateTM").toString();
                    sRemark1 = senderobj.get("Remark").toString();
                    sTxHash1 = senderobj.get("TxHash").toString();
                    fnFormData.setAttrib32(sName1);
                    fnFormData.setAttrib12(sHash1);
                    fnFormData.setAttrib33(sCreateTM1);
                    fnFormData.setAttrib37(sRemark1);
                    fnFormData.setAttrib58(sTxHash1);
                    ChainmakerTransaction.TransactionInfo transactionInfo = null;

                    try {
                        transactionInfo = chainClient.getTxByTxId(sTxHash1, 10000);
                    } catch (SdkException e) {
                        e.printStackTrace();
                    }

                    fnFormData.setAttrib40(transactionInfo.getTransaction().getPayload().getChainId());
                    fnFormData.setAttrib41(transactionInfo.getTransaction().getPayload().getContractName());
                    fnFormData.setAttrib42("");  //合约版本号
                    fnFormData.setAttrib49(String.valueOf(transactionInfo.getTransaction().getPayload().getTimestamp()));

                    fnFormData.setAttrib43(transactionInfo.getTransaction().getPayload().getTxId());
                    fnFormData.setAttrib44(String.valueOf(transactionInfo.getBlockHeight()));
                    fnFormData.setAttrib45(transactionInfo.getTransaction().getSender().getSigner().getOrgId());

                }

                if ((receiverobj != null) && (receiverobj.size() > 0)) {
                    sName2 = receiverobj.get("Name").toString();
                    sHash2 = receiverobj.get("Hash").toString();
                    sCreateTM2 = receiverobj.get("CreateTM").toString();
                    sRemark2 = receiverobj.get("Remark").toString();
                    sTxHash2 = receiverobj.get("TxHash").toString();
                    fnFormData.setAttrib35(sName2);
                    fnFormData.setAttrib13(sHash2);
                    fnFormData.setAttrib36(sCreateTM2);
                    fnFormData.setAttrib38(sRemark2);
                    fnFormData.setAttrib59(sTxHash2);

                    ChainmakerTransaction.TransactionInfo transactionInfo = null;

                    try {
                        transactionInfo = chainClient.getTxByTxId(sTxHash2, 10000);
                    } catch (SdkException e) {
                        e.printStackTrace();
                    }

                    fnFormData.setAttrib40(transactionInfo.getTransaction().getPayload().getChainId());
                    fnFormData.setAttrib41(transactionInfo.getTransaction().getPayload().getContractName());
                    fnFormData.setAttrib42("");  //合约版本号
                    fnFormData.setAttrib50(String.valueOf(transactionInfo.getTransaction().getPayload().getTimestamp()));

                    fnFormData.setAttrib46(transactionInfo.getTransaction().getPayload().getTxId());
                    fnFormData.setAttrib47(String.valueOf(transactionInfo.getBlockHeight()));
                    fnFormData.setAttrib48(transactionInfo.getTransaction().getSender().getSigner().getOrgId());

                }

                if ((senderobj != null) && (senderobj.size() > 0) && (receiverobj != null) && (receiverobj.size() > 0)) {
                    if ((sName1 == sName2) && (sHash1 == sHash2) && (sCreateTM1 == sCreateTM2) && (sRemark1 == sRemark2)) {
                        fnFormData.setAttrib39("是");
                    } else {
                        fnFormData.setAttrib39("否");
                    }
                }

                Record rd = Db.findFirst("select * from fn_form_data where attrib_01 = ? and attrib_31 = ?", "273fc75a0c834f248203a272f8ca7840", orderId);
                if (rd != null) {   //已经存在
                    fnFormData.setConflictId(rd.getStr("conflict_id"));
                    if (!fnFormData.update()) {
                        System.out.println("\n链上存证数据缓存更新失败, orderId: " + orderId);
                    }
                } else {
                    String cid = Helper.bulidUUID();
                    fnFormData.setConflictId(cid);
                    fnFormData.setRowId(cid);
                    fnFormData.setAttrib01("273fc75a0c834f248203a272f8ca7840");
                    fnFormData.setAttrib54(sType);

                    if (!fnFormData.save()) {
                        System.out.println("\n链上存证数据缓存保存失败, orderId: " + orderId);
                    }
                }
            }
        }
        return true;
    }

    /**
     * 将所有证据项存入数据库
     *
     * @param chainClient  区块链客户端
     * @param contractName 合约名称
     * @return 存储成功返回 true，否则返回 false
     * @throws Exception 发生错误时抛出异常
     */
    public static boolean getAllStatesToDb(ChainClient chainClient, String contractName) throws Exception {

        Integer allSize = getStateSize(chainClient, contractName);

        if (allSize == 0) {
            return true;
        }

        int pagesize = 100;

        // 相除并取商
        int pagenum = allSize / pagesize;
        // 相除并取余数
        int remainder = allSize % pagesize;

        if (remainder > 0) {
            pagenum++;
        }

        //一页一页取，每次100条
        for (int ii = 1; ii <= pagenum; ii++) {
            Map<String, byte[]> paramMap = new HashMap<>();

            JSONObject page = new JSONObject();
            page.put("PageSize", pagesize);
            page.put("PageNum", pagenum);

            paramMap.put("data", page.toString().getBytes());

            ResultOuterClass.TxResponse responseInfo = null;
            try {
                responseInfo = chainClient.queryContract(contractName, "getStates",
                        null, paramMap, 10000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("getOrders 执行合约结果：");
            System.out.println(responseInfo);

            if (responseInfo.getContractResult().getResult() == null || responseInfo.getContractResult().getMessage().equals("Fail")) {
                return false;
            }
            String str = ByteString.copyFromUtf8(responseInfo.getContractResult().getResult().toStringUtf8()).toStringUtf8();

            // 将字符串转换为JsonArray
            Gson gson = new Gson();
            JsonArray jsonArray = gson.fromJson(str, JsonArray.class);
            if (jsonArray == null) {
                return false;
            }

            for (int i = 0; i < jsonArray.size(); i++) {
                String sData = jsonArray.get(i).toString();
                JSONObject shareObject = JSONUtil.toBean(sData, JSONObject.class);
                JSONObject senderobj = shareObject.getJSONObject("Sender");
                JSONObject receiverobj = shareObject.getJSONObject("Receiver");

                FnFormData fnFormData = new FnFormData();

                String orderId = shareObject.get("StateId").toString();
                String sType = "状态数据";
                String sName1 = "";
                String sHash1 = "";
                String sCreateTM1 = "";
                String sRemark1 = "";
                String sTxHash1 = "";
                String sName2 = "";
                String sHash2 = "";
                String sCreateTM2 = "";
                String sRemark2 = "";
                String sTxHash2 = "";
                fnFormData.setAttrib31(orderId);

                if ((senderobj != null) && (senderobj.size() > 0)) {
                    sName1 = senderobj.get("Name").toString();
                    sHash1 = senderobj.get("Hash").toString();
                    sCreateTM1 = senderobj.get("CreateTM").toString();
                    sRemark1 = senderobj.get("Remark").toString();
                    sTxHash1 = senderobj.get("TxHash").toString();
                    fnFormData.setAttrib32(sName1);
                    fnFormData.setAttrib12(sHash1);
                    fnFormData.setAttrib33(sCreateTM1);
                    fnFormData.setAttrib37(sRemark1);
                    fnFormData.setAttrib58(sTxHash1);
                    ChainmakerTransaction.TransactionInfo transactionInfo = null;

                    try {
                        transactionInfo = chainClient.getTxByTxId(sTxHash1, 10000);
                    } catch (SdkException e) {
                        e.printStackTrace();
                    }

                    fnFormData.setAttrib40(transactionInfo.getTransaction().getPayload().getChainId());
                    fnFormData.setAttrib41(transactionInfo.getTransaction().getPayload().getContractName());
                    fnFormData.setAttrib42("");  //合约版本号
                    fnFormData.setAttrib49(String.valueOf(transactionInfo.getTransaction().getPayload().getTimestamp()));

                    fnFormData.setAttrib43(transactionInfo.getTransaction().getPayload().getTxId());
                    fnFormData.setAttrib44(String.valueOf(transactionInfo.getBlockHeight()));
                    fnFormData.setAttrib45(transactionInfo.getTransaction().getSender().getSigner().getOrgId());

                }

                if ((receiverobj != null) && (receiverobj.size() > 0)) {
                    sName2 = receiverobj.get("Name").toString();
                    sHash2 = receiverobj.get("Hash").toString();
                    sCreateTM2 = receiverobj.get("CreateTM").toString();
                    sRemark2 = receiverobj.get("Remark").toString();
                    sTxHash2 = receiverobj.get("TxHash").toString();
                    fnFormData.setAttrib35(sName2);
                    fnFormData.setAttrib13(sHash2);
                    fnFormData.setAttrib36(sCreateTM2);
                    fnFormData.setAttrib38(sRemark2);
                    fnFormData.setAttrib59(sTxHash2);

                    ChainmakerTransaction.TransactionInfo transactionInfo = null;

                    try {
                        transactionInfo = chainClient.getTxByTxId(sTxHash2, 10000);
                    } catch (SdkException e) {
                        e.printStackTrace();
                    }

                    fnFormData.setAttrib40(transactionInfo.getTransaction().getPayload().getChainId());
                    fnFormData.setAttrib41(transactionInfo.getTransaction().getPayload().getContractName());
                    fnFormData.setAttrib42("");  //合约版本号
                    fnFormData.setAttrib50(String.valueOf(transactionInfo.getTransaction().getPayload().getTimestamp()));

                    fnFormData.setAttrib46(transactionInfo.getTransaction().getPayload().getTxId());
                    fnFormData.setAttrib47(String.valueOf(transactionInfo.getBlockHeight()));
                    fnFormData.setAttrib48(transactionInfo.getTransaction().getSender().getSigner().getOrgId());

                }

                if ((senderobj != null) && (senderobj.size() > 0) && (receiverobj != null) && (receiverobj.size() > 0)) {
                    if ((sName1 == sName2) && (sHash1 == sHash2) && (sCreateTM1 == sCreateTM2) && (sRemark1 == sRemark2)) {
                        fnFormData.setAttrib39("是");
                    } else {
                        fnFormData.setAttrib39("否");
                    }
                }

                Record rd = Db.findFirst("select * from fn_form_data where attrib_01 = ? and attrib_31 = ?", "273fc75a0c834f248203a272f8ca7840", orderId);
                if (rd != null) {   //已经存在
                    fnFormData.setConflictId(rd.getStr("conflict_id"));
                    if (!fnFormData.update()) {
                        System.out.println("\n链上存证数据缓存更新失败, orderId: " + orderId);
                    }
                } else {
                    String cid = Helper.bulidUUID();
                    fnFormData.setConflictId(cid);
                    fnFormData.setRowId(cid);
                    fnFormData.setAttrib01("273fc75a0c834f248203a272f8ca7840");
                    fnFormData.setAttrib54(sType);

                    if (!fnFormData.save()) {
                        System.out.println("\n链上存证数据缓存保存失败, orderId: " + orderId);
                    }
                }
            }
        }
        return true;
    }

    public static ShareItem jsonObjectToShareItem(String jsonstr) {

        if (jsonstr.equals("")) {
            return null;
        }
        JSONObject jsonObject = JSONUtil.toBean(jsonstr, JSONObject.class);
        JSONObject senderobj = jsonObject.getJSONObject("Sender");
        JSONObject receiverobj = jsonObject.getJSONObject("Receiver");
        BaseItem sender = null;
        BaseItem receiver = null;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX");
        if (senderobj.size() > 0) {
            sender = new BaseItem(senderobj.get("Name").toString().getBytes(), senderobj.get("Hash").toString().getBytes(), senderobj.getBigInteger("CreateTM"), senderobj.get("Remark").toString().getBytes(), senderobj.get("TxHash").toString().getBytes());
        } else {
            sender = new BaseItem("".getBytes(), null, new BigInteger("0"), "".getBytes(), "".getBytes());
        }

        if (receiverobj.size() > 0) {
            receiver = new BaseItem(receiverobj.get("Name").toString().getBytes(), receiverobj.get("Hash").toString().getBytes(), receiverobj.getBigInteger("CreateTM"), receiverobj.get("Remark").toString().getBytes(), receiverobj.get("TxHash").toString().getBytes());
        } else {
            receiver = new BaseItem("".getBytes(), null, new BigInteger("0"), "".getBytes(), "".getBytes());
        }

        return new ShareItem(sender, receiver);

    }

    public static ShareItem jsonObjectToOrderShare(String jsonstr) {

        if (jsonstr.equals("")) {
            return null;
        }
        JSONObject jsonObject = JSONUtil.toBean(jsonstr, JSONObject.class);
        JSONObject senderobj = jsonObject.getJSONObject("Sender");
        JSONObject receiverobj = jsonObject.getJSONObject("Receiver");
        BaseItem sender = null;
        BaseItem receiver = null;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX");
        if (senderobj.size() > 0) {
            sender = new BaseItem(senderobj.get("Name").toString().getBytes(), senderobj.get("Hash").toString().getBytes(), senderobj.getBigInteger("CreateTM"), senderobj.get("Remark").toString().getBytes(), senderobj.get("TxHash").toString().getBytes());
        } else {
            sender = new BaseItem("".getBytes(), null, new BigInteger("0"), "".getBytes(), "".getBytes());
        }

        if (receiverobj.size() > 0) {
            receiver = new BaseItem(receiverobj.get("Name").toString().getBytes(), receiverobj.get("Hash").toString().getBytes(), receiverobj.getBigInteger("CreateTM"), receiverobj.get("Remark").toString().getBytes(), receiverobj.get("TxHash").toString().getBytes())
            ;
        } else {
            receiver = new BaseItem("".getBytes(), null, new BigInteger("0"), "".getBytes(), "".getBytes());
        }

        return new ShareItem(sender, receiver);

    }

    /**
     * 授权
     *
     * @param chainClient    区块链客户端
     * @param contract       合约名称
     * @param chainAccoutCID 授权区块链账号的conflict_id
     * @param category       授权类别
     * @param chainAccoutCID 授权类别区块链账号的conflict_id
     * @return 如果授权成功，返回 true；否则返回 false
     */
    public static boolean authorize(ChainClient chainClient, String contract, String chainAccoutCID, String category) throws Exception {
        Record rd = Db.findFirst("select * from fn_form_data where attrib_01 = ? and  conflict_id = ?", "d3720c95544c48d4875c61ff57685233", chainAccoutCID);

        if (rd == null) {
            return false;
        }
        User user = InitClient.getClientUser(rd.getStr("ATTRIB_05"), rd.getStr("ATTRIB_13").getBytes(), rd.getStr("ATTRIB_20").getBytes(), rd.getStr("ATTRIB_59").getBytes(), rd.getStr("ATTRIB_60").getBytes());        Map<String, byte[]> paramMap = new HashMap<>();
        String fromAddress = CryptoUtils.certToAddrStr(user.getCertificate(), ChainConfigOuterClass.AddrType.ETHEREUM);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("account", fromAddress);
        jsonObject.put("category", category);
        System.out.println(jsonObject.toString());

        paramMap.put("data", jsonObject.toString().getBytes());

        ResultOuterClass.TxResponse responseInfo = null;
        try {
            responseInfo = chainClient.invokeContract(contract, "authorize",
                    null, paramMap, 10000, 10000);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        System.out.println("authorize 执行合约结果：");
        System.out.println(responseInfo);

        return true;
    }


    /**
     * 授权
     *
     * @param chainClient    区块链客户端
     * @param contract       合约名称
     * @param orgId 区块链组织ID
     * @param certUserName 区块链用户账号
     * @param category       授权类别
     * @return 如果授权成功，返回 true；否则返回 false
     */
    public static boolean authorizeTwo(ChainClient chainClient, String contract,String orgId,String certUserName , String category) throws Exception {
        Record signRecord = Db.findFirst("SELECT cert,private_key,cert_use FROM cmb_cert WHERE cert_user_name = ? and org_id = ?  and cert_use = '0' ", certUserName, orgId);
        Record tlsRecord = Db.findFirst("SELECT cert,private_key,cert_use FROM cmb_cert WHERE cert_user_name = ? and org_id = ?  and cert_use = '1' ", certUserName, orgId);
        if (signRecord==null || tlsRecord==null) {
            return false;
        }
        User user = InitClient.getClientUser(orgId, signRecord.getStr("private_key").getBytes(), signRecord.getStr("cert").getBytes(), tlsRecord.getStr("private_key").getBytes(), tlsRecord.getStr("cert").getBytes());        Map<String, byte[]> paramMap = new HashMap<>();
        String fromAddress = CryptoUtils.certToAddrStr(user.getCertificate(), ChainConfigOuterClass.AddrType.ETHEREUM);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("account", fromAddress);
        jsonObject.put("category", category);
        paramMap.put("data", jsonObject.toString().getBytes());
        ResultOuterClass.TxResponse responseInfo = null;
        try {
            responseInfo = chainClient.invokeContract(contract, "authorize",
                    null, paramMap, 10000, 10000);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        System.out.println("authorize 执行合约结果：");
        System.out.println(responseInfo);
        return true;
    }


}
